<?php

namespace app\admin\controller;

use think\facade\Db;
use think\facade\Request;

class Cdkey extends Common
{
    private $table = 'cdkey';

    public function generate()
    {
        $params = Request::param();

        $vip_id = getParam($params, 'vip_id');

        $vip_info = Db::name('vips')->where("id=" . $vip_id)->find();

        $num = getParam($params, 'num');

        $data = array();

        $success_count = 0;
        for ($i = 0; $i < $num; $i++) {
            $data['code'] = $this->getInviteCode();
            $data['title'] = $vip_info['title'];
            $data['duration'] = $vip_info['times'];
            $data['vip_id'] = $vip_id;
            $lastid = Db::name($this->table)->insertGetId($data);
            if ($lastid > 0) {
                $success_count++;
            }
        }

        singleJson($success_count, '出错');
    }

    /**
     * 生成邀请码
     * @param $userId
     * @return string
     */
    public function getInviteCode($userId = 0)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $num = strlen($chars);
        $str = '';
        while ($userId > 0) {
            $mod = $userId % $num;
            $userId = ($userId - $mod) / $num;
            $str = $chars[$mod] . $str;
        }

        // 不足用随机字符串补充，10表示邀请码邀请10位
        $str = str_pad($str, 12, self::createNonceStr(12 - strlen($str)), STR_PAD_LEFT);
        return $str;
    }

    protected static function createNonceStr($length = 16)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

}
